package com.devunion.bogdan.model.command;

import javax.swing.event.EventListenerList;

/**
 * @author Viktar Liaskovich
 */
public class CommandDispatcher {
    private static CommandDispatcher instance = new CommandDispatcher();

    private EventListenerList listenerList = new EventListenerList();

    public static CommandDispatcher getInstance() {
        return instance;
    }

    public void addCommandReceiver(CommandReceiver receiver) {
        listenerList.add(CommandReceiver.class, receiver);
    }

    public void removeCommandReceiver(CommandReceiver receiver) {
        listenerList.remove(CommandReceiver.class, receiver);
    }

    public void dispatch(Command command) {
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();

        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length - 1; i >= 0; i--) {
            if (listeners[i] == CommandReceiver.class) {
                ((CommandReceiver) listeners[i + 1]).executeCommand(command);
            }
        }
    }
}
